package com.easy.dfcapi.service.impl;

import com.easy.common.bean.Result;
import com.easy.common.constant.EnumConfig;
import com.easy.common.util.Utility;
import com.easy.common.utils.SpringContextHolder;
import com.easy.dfcapi.entity.*;
import com.easy.dfcapi.mapper.*;
import com.easy.dfcapi.res.*;
import com.easy.dfcapi.service.ApiActivityService;
import com.easy.dfcapi.utils.ApiSessionUser;
import com.easy.dfcapi.utils.ServletHelper;
import com.easy.dfcapi.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by VULCANTSeries on 2017/5/10.
 */
@Service
@Transactional(readOnly = true)
public class ApiActivityServiceImpl implements ApiActivityService {

    @Autowired
    private ApiActivityMapper activityMapper;

    @Autowired
    private ApiActivityEnrollMapper activityEnrollMapper;

    @Autowired
    private ApiUserMapper userMapper;

    @Autowired
    private ApiActivityProductMapper activityProductMapper;

    @Autowired
    private ApiProductMapper productMapper;

    @Autowired
    private ApiActivityLiveMapper activityLiveMapper;


    @Override
    @Transactional(readOnly = false)
    public Result ActivityEnrollAdd(Response<ActivityEnrollRes> response) throws Exception{

        Result rt = new Result();
        try{
            ActivityEnrollRes data = response.getData(ActivityEnrollRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            Integer userId = sessionUser.getUserId();
            Integer storeId = sessionUser.getStoreId();

            ApiActivity activity = activityMapper.get(data.getActivityId());
            if(userId < 1 || activity == null || storeId < 1){
                rt.setStatus(EnumConfig.S_CODE.PARAM_ERROR);
                return rt;

            }
            Date now = new Date();
            ApiActivityEnroll enroll = new ApiActivityEnroll();
            ApiActivityProduct product = new ApiActivityProduct();
            ApiActivityLive live = new ApiActivityLive();
            enroll.setStoreId(storeId);
            enroll.setTypeId(data.getTypeId());
            enroll.setActivityId(activity.getActivityId());
            enroll.setContactName(data.getContactName());
            enroll.setContactPhone(data.getContactPhone());
            enroll.setStartTime(data.getStartTime());
            enroll.setEndTime(data.getEndTime());
            enroll.setStatus("1");
            enroll.setCreateId(userId);
            enroll.setUpdateId(userId);
            enroll.setCreateTime(now);
            enroll.setUpdateTime(now);
            enroll.setAmnt(activity.getAmnt());
            enroll.preInsert(now);

            activityEnrollMapper.insert(enroll);
            for(int i=0;i< data.getProductList().size();i++) {
                ActivityEnrollProductRes pr = data.getProductList().get(i);
                ApiProduct product1 = productMapper.get(pr.getProductId());
                if (product1 != null) {
                    product.setEnrollId(enroll.getEnrollId());
                    product.setStoreId(storeId);
                    product.setProductId(product1.getProductId());
                    product.setPrice(pr.getPrice());
                    product.setNum(pr.getNum());
                    product.setStatus("0");
                    activityProductMapper.insert(product);
                }
            }
            for(int i=0;i< data.getLiveList().size();i++) {
                /*
                ActivityEnrollLive lv = data.getLiveList().get(i);
                live.setTitle(Utility.null2Empty(lv.getLiveTitle()));
                live.setCoverPlan(Utility.null2Empty(lv.getCoverPlan()));
                live.setVideoUrl(Utility.null2Empty("live"+enroll.getId()));
                live.setActivityId(enroll.getId());
                live.setFactoryId(enroll.getFactoryId());
                live.setLiveStatus("0");
                live.setAuditStatus(enroll.getStatus());
                live.setStartDate(enroll.getStartTime());
                live.setCreateDate(now);
                live.setDuration(100);
                live.setUserId(userId);
                live.setHavePay(0);
                activityEnrollMapper.insertLive(live);
                */
            }
            rt.setStatus(EnumConfig.S_CODE.OK);
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }

        return rt;
    }



    @Override
    @Transactional(readOnly = false)
    public Result ActivityEnrollCancel(Response<ActivityEnrollQueryRes> response)  throws Exception{
        Result rt = new Result();
        try{
            ActivityEnrollQueryRes data = response.getData(ActivityEnrollQueryRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            activityMapper.ActivityEnrollCancel(data.getEnrollId());
            rt.setStatus(EnumConfig.S_CODE.OK);
            //rt.setData(list);
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }

        return rt;
    }

    @Override
    public Result ActivityEnrollDetail(Response<ActivityEnrollQueryRes> response)  throws Exception{
        Result rt = new Result();
        try{
            ActivityEnrollQueryRes data = response.getData(ActivityEnrollQueryRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            Map<String,Object> map = activityMapper.ActivityEnrollDetail(data.getEnrollId());
            if(map==null){
                rt.setStatus(EnumConfig.S_CODE.OK);
                rt.setData(new HashMap());
                return rt;
            }
            String enrollId = (String)map.get("id");
            Integer typeId = (Integer)map.get("typeId");

            List<Map<String,Object>>productList = activityMapper.ActivityEnrollProduct(enrollId);
            if(typeId==2){
                map.put("productList",productList);
            }
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(map);
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }

        return rt;
    }

    @Override
    public Result ActivityEnrollList(Response<ActivityEnrollQueryRes> response)  throws Exception{
        Result rt = new Result();
        try{

            ActivityEnrollQueryRes data = response.getData(ActivityEnrollQueryRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }
            Integer storeId = sessionUser.getStoreId();

            List<Map<String,Object>> list = activityMapper.ActivityEnrollList(data);

            for(int i=0;i<list.size();i++){
                Map<String,Object> map = list.get(i);
                String status = (String)map.get("status");
                if(status.equals("2")){
                    Map<String,Object> payMap = new HashMap<String,Object>();
                    payMap.put("payId",map.get("id"));
                    payMap.put("payName","enrollPay");
                    payMap.put("payAmnt",map.get("amnt"));
                    payMap.put("payStoreId",storeId);
                    payMap.put("payProductName",map.get("subject")+"活动报名费");
                    payMap.put("payProductDesc","参加"+map.get("startTime")+map.get("subject")+"活动报名费");

                    payMap.put("payMode","aliPay,weChatPay");
                    map.put("payInfo",payMap);
                }
                String enrollId = (String)map.get("id");
                List<Map<String,Object>>productList = activityMapper.ActivityEnrollProduct(enrollId);
                map.put("productList",productList);
                List<ApiActivityLive>liveList = activityLiveMapper.getLiveList(enrollId);
                map.put("liveList",liveList);
                list.set(i, map);

                //list.set(i,map);
            }
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(list);
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }

        return rt;
    }

    @Override
    public Result ActivityList(Response<ActivityRes> response)  throws Exception{
        Result rt = new Result();
        try{
            ActivityRes data = response.getData(ActivityRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            List<Map<String,Object>> list = activityMapper.ActivityList(data);
            Date tdate = new Date(0);
            Integer day = Utility.getDaySpan(data.getStartDate(), data.getEndDate()) + 1;
            List []ls = new ArrayList[day];
            //Map<String,Object> []map = new HashMap[day];

            for(int i =0; i < list.size(); i++){
                Map<String,Object> activity = list.get(i);
                Integer sday = Utility.getDaySpan(data.getStartDate(), (Date)activity.get("startTime"));
                Integer eday = Utility.getDaySpan(data.getEndDate(), (Date)activity.get("endTime"));
                if(sday<1)sday=0;
                if(eday>=day)eday=day;
                for(int j = sday;j< eday;j++){
                    if(ls[j] == null) ls[j]= new ArrayList();
                    ls[j].add(activity);
                }
            }

            List lst = new ArrayList();
            for(int i = 0; i < day; i++) {
                if(ls[i]==null || ls[i].size()<1)continue;
                Map tmap = new HashMap();
                tmap.put("tdate",Utility.getDateStr(Utility.getDayAfter(data.getStartDate(),i)));
                tmap.put("activity",ls[i]);
                lst.add(tmap);
            }
            rt.setStatus(EnumConfig.S_CODE.OK);
            rt.setData(lst);
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }

        return rt;
    }

    @Override
    @Transactional(readOnly = false)
    public Result ActivityEnrollPay(Response<PayInfoRes> response)  throws Exception{
        Result rt = new Result();
        try{

            PayInfoRes data = response.getData(PayInfoRes.class);
            ApiSessionUser sessionUser = ServletHelper.getSessionUserByToken(response.getToken());
            if(sessionUser == null){
                rt.setStatus(EnumConfig.S_CODE.NOT_USER);
                return rt;
            }

            ApiUser user = userMapper.getByUserId(sessionUser.getUserId());
            if(user==null){
                rt.setStatus(EnumConfig.S_CODE.VALID_FAILED);
                return rt;
            }

            Map<String,Object> map = new HashMap<String,Object>();

            Date now = new Date();
            PayProductInfo info = new PayProductInfo();
            info.setTradeNo(Util.getOrderItemNo());
            info.setTotalAmnt(new BigDecimal(1));
            info.setProductName(data.getPayProductName());
            info.setProductDesc(data.getPayProductDesc());
            info.setCreateTime(now);
            info.setExpireTime(new Date(now.getTime()+900000));
            //info.setNotifyUrl(url+"${apiPath}/factory/aliNotify");
            info.setNotifyUrl(SpringContextHolder.getContextPath() +"/AliNotify");

            if(data.getPayMode().equals("aliPay")){
                AliPayInfo aliPay = new AliPayInfo();
                String zBody = aliPay.getAliPayInfo(info);
                map.put("payId",data.getPayId());
                map.put("tradeNo",info.getTradeNo());
                map.put("payName","aliPay");
                map.put("payInfo",zBody);

                activityEnrollMapper.updateTradeNo(data.getPayId(),info.getTradeNo());

            }
            if(data.getPayMode().equals("weChatPay")){
                AliPayInfo aliPay = new AliPayInfo();
                WeChatPayInfo weChatPay = new WeChatPayInfo();
                map.put("payId",data.getPayId());
                map.put("tradeNo",info.getTradeNo());
                map.put("payName","weChatPay");
                map.put("payInfo",weChatPay.getWeChatPayInfo(info));
            }
            rt.setData(map);
            rt.setStatus(EnumConfig.S_CODE.OK);
        }catch(Exception ex){
            rt.setStatus(EnumConfig.S_CODE.FAIL);
            throw ex;
        }

        return rt;

    }

    @Override
    @Transactional(readOnly = false)
    public String AliNotify(AliNotifyRes aliNotify) throws Exception{
        String tradeStatus = aliNotify.getTradeStatus();
        if(tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")){//订单支付完成
            String outTradeNo = aliNotify.getOutTradeNo();
            ApiActivityEnroll activityEnroll = activityEnrollMapper.findByTradeNo(outTradeNo);
            if(activityEnroll != null){
                activityEnrollMapper.updateSucessStatus(activityEnroll.getId());
            }

        }
        else if(tradeStatus.equals("TRADE_CLOSED")){//订单关闭
            //String outTradeNo = aliNotify.getOut_trade_no();
            //DfcFactoryUpgrade upgrade = factoryUpgradeMapper.findByTradeNo(outTradeNo);
            //if(upgrade != null){
            //    factorySetMapper.updateFactoryType(upgrade.getFactoryId(),upgrade.getUpgradeId());
            //    factoryUpgradeMapper.updateFailStatus(upgrade.getId());
            //}
        }
        else {//其他错误
            //String outTradeNo = aliNotify.getOut_trade_no();
            //DfcFactoryUpgrade upgrade = factoryUpgradeMapper.findByTradeNo(outTradeNo);
            //if(upgrade != null){
            //    factorySetMapper.updateFactoryType(upgrade.getFactoryId(),upgrade.getUpgradeId());
            //    factoryUpgradeMapper.updateFailStatus(upgrade.getId());
            //}
        }
        return "success";
    }


}
